const Score = require('../models/Score');
const { parseScoreByPositionCode } = require('../utils/fileParser');

// 存储分数数据到 MongoDB
async function storeScoreData(province, city, date, positionCode) {
  try {
    // 解析 Excel 文件
    const result = await parseScoreByPositionCode(province, city, date, positionCode);
    
    if (!result.data || result.data.length === 0) {
      console.log('没有找到分数数据');
      return { success: false, message: '没有找到分数数据' };
    }
    
    // 批量插入数据到 MongoDB
    const operations = result.data.map(score => ({
      updateOne: {
        filter: { 
          examNumber: score.examNumber,
          positionCode: result.positionCode,
          province: result.province,
          city: result.city,
          date: result.date
        },
        update: {
          $set: {
            ...score,
            province: result.province,
            city: result.city,
            date: result.date,
            positionCode: result.positionCode,
            updatedAt: new Date()
          }
        },
        upsert: true
      }
    }));
    
    const bulkWriteResult = await Score.bulkWrite(operations);
    
    console.log(`成功存储分数数据: ${bulkWriteResult.upsertedCount} 条新增, ${bulkWriteResult.modifiedCount} 条更新`);
    
    return { 
      success: true, 
      insertedCount: bulkWriteResult.upsertedCount,
      modifiedCount: bulkWriteResult.modifiedCount,
      data: result.data
    };
  } catch (error) {
    console.error('存储分数数据失败:', error);
    throw error;
  }
}

// 查询分数数据
async function queryScores(province, city, date, positionCode, filters = {}) {
  try {
    // 构建查询条件
    const query = { province, city, date, positionCode, ...filters };
    
    // 执行查询
    const scores = await Score.find(query).sort({ rank: 1 });
    
    return {
      success: true,
      count: scores.length,
      data: scores
    };
  } catch (error) {
    console.error('查询分数数据失败:', error);
    throw error;
  }
}

// 删除分数数据
async function deleteScoreData(province, city, date, positionCode = null) {
  try {
    const query = { province, city, date };
    if (positionCode) {
      query.positionCode = positionCode;
    }
    
    const result = await Score.deleteMany(query);
    
    return {
      success: true,
      deletedCount: result.deletedCount
    };
  } catch (error) {
    console.error('删除分数数据失败:', error);
    throw error;
  }
}

module.exports = {
  storeScoreData,
  queryScores,
  deleteScoreData
};